<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2024-12-16 20:05:01
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-02-26 15:48:40
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\basicInformation\skuManage\skuInformation\components\addModifPop.vue
-->

<template>
  <pb-popup v-model="isShow" :title="`${skuForm.skuId ? '修改' : '添加'}食材SKU`" @cancelFn="offPopup" @confirmFn="onSave"
    Width="1240">
    <div v-loading="loading">


      <el-form style="width: 100%" :model="skuForm" label-width="auto" inline ref="ruleFormRef1" :rules="rules"
        validate-on-rule-change>
        <div style="width: 100%" class="flex justify-between">
          <div>
            <el-form-item label="SKU编码：" style="width: 200px">
              {{ skuForm.skuCode }}
            </el-form-item>
            <el-form-item label="助记码：" prop="mnemonicCode">
              <div v-if="!innerVisible">
                <span>
                  {{ skuForm.mnemonicCode }}
                </span>
                <pb-icon name="edit" v-show="skuForm.mnemonicCode && skuForm.isSystemData != 1" color="rgba(0,0,0,0.25)"
                  class="ml-2" @click="innerVisible = true"></pb-icon>
              </div>
              <pb-input v-model.trim="skuForm.mnemonicCode" maxlength="50" v-else @blur="CheckMnemonic"></pb-input>

            </el-form-item>
          </div>
          <el-form-item label="纳入库存统计">
            <el-switch v-model="skuForm.isStocked" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </div>
      </el-form>

      <el-form style="width: 100%" :model="skuForm" label-width="auto" inline label-position="top" ref="ruleFormRef"
        :rules="rules" validate-on-rule-change>

        <div style="width: 100%;display: flex;">

          <el-form-item label="SKU类别" prop="skuClassCode">
            <!-- <pb-tree-select v-model="skuForm.skuClassCode" :Data="treeData"
            :defaultProps="{ children: 'children', label: 'skuClassName', value: 'skuClassCode' }" /> -->
            <pb-tree-select v-model="skuForm.skuClassCode" :Data="treeData" :disabled="skuForm.skuId"
              :defaultProps="{ children: 'children', label: 'skuClassName', value: 'skuClassCode' }" />
          </el-form-item>
          <el-form-item label="SKU名称" prop="skuName">
            <pb-input v-model.trim="skuForm.skuName" placeholder="请输入SKU名称" maxlength="30"></pb-input>
          </el-form-item>
          <el-form-item label="SKU条码" prop="barCode">
            <pb-input v-model.trim="skuForm.barCode" minlength="4" maxlength="10" placeholder="请输入SKU条码"></pb-input>
          </el-form-item>
        </div>

        <el-form-item label="计量单位(采购)" prop="accountingUnit">
          <pb-select v-model="skuForm.accountingUnit" :options="unitsList" :disabled="skuForm.skuId" placeholder="请选择单位"
            keys="skuPackagingUnitId" label="packagingUnitName" @change="changeOne"></pb-select>
        </el-form-item>
        <el-form-item label="计量单位(库存)" prop="inventoryUnit">
          <pb-select v-model="skuForm.inventoryUnit" :options="unitsList" :disabled="skuForm.skuId" placeholder="请选择单位"
            keys="skuPackagingUnitId" label="packagingUnitName" @change="changeTwo"></pb-select>
        </el-form-item>
        <el-form-item label="最小单位" prop="minimumUnit">
          <pb-select v-model="skuForm.minimumUnit" :options="unitsList" :disabled="skuForm.skuId" placeholder="请选择单位"
            keys="skuPackagingUnitId" label="packagingUnitName" @change="changeThree"></pb-select>
        </el-form-item>
        <el-form-item prop="inventoryScaleFactor">
          <template #label="{ row }">
            <div class="inline-block">换算关系
              <span class="sub-label">(采购与库存)</span>
            </div>
          </template>
          1
          <span class="ml-1 mr-1">
            {{ conversionOne }}
          </span>
          <span class=" mr-1">
            =
          </span>
          <el-input v-model.trim="skuForm.inventoryScaleFactor" :disabled="skuForm.skuId" style="width: 100px;">
            <template #append>{{ conversionTwo }}</template>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-right: 0;" prop="minimumScaleFactor">
          <template #label="{ row }">
            <div class="inline-block">换算关系
              <span class="sub-label">(库存与最小单位)</span>
            </div>
          </template>
          1
          <span class="ml-1 mr-1">
            {{ conversionTwo }}
          </span>
          <span class=" mr-1">
            =
          </span>
          <el-input v-model.trim="skuForm.minimumScaleFactor" :disabled="skuForm.skuId" style="width: 100px;">
            <template #append>{{ conversionThree }}</template>
          </el-input>
        </el-form-item>

        <el-form-item label="规格">
          <pb-input v-model.trim="skuForm.specifications" maxlength="20" placeholder="请输入规格"></pb-input>
        </el-form-item>
        <el-form-item label="单位重量（kg）" prop="unitWeight">
          <pb-input v-model.trim="skuForm.unitWeight" maxlength="5" placeholder="请输入单位重量"></pb-input>
        </el-form-item>
        <el-form-item label="损耗率(%)" prop="lossRate">
          <pb-input v-model.trim="skuForm.lossRate" maxlength="10" placeholder="请输入损耗率"></pb-input>
        </el-form-item>
        <el-form-item label="出成率(%)" prop="recoveryRate" style="margin-right: 0;">
          <pb-input v-model.trim="skuForm.recoveryRate" maxlength="10" placeholder="请输入损耗率"></pb-input>
        </el-form-item>

        <el-form-item label="采购周期">
          <pb-select v-model.trim="skuForm.purchasingCycle" :options="purCycle" placeholder="请选择单位"
            keys="purchasingCycleCode" label="purchasingCycleName"></pb-select>
        </el-form-item>

        <el-form-item label="产地" prop="placeOrigin">
          <pb-input v-model.trim="skuForm.placeOrigin" maxlength="10" placeholder="请输入产地"></pb-input>
        </el-form-item>

        <el-form-item label="匹配SPU" prop="spuName">
          <el-autocomplete v-model="skuForm.spuCommonlyName" :disabled="skuForm.skuId" :fetch-suggestions="handleSearch"
            clearable placeholder="请输入SPU名称" style="width: 240px;" @select="handleSelect">
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="品牌" prop="brand">
          <pb-input v-model.trim="skuForm.brand" maxlength="10" placeholder="请输入品牌"></pb-input>
        </el-form-item>
        <el-form-item label="季节">
          <pb-select v-model="skuForm.season" multiple :options="seasonList" placeholder="请选择季节" keys="label"
            label="label"></pb-select>
        </el-form-item>
        <el-form-item label="外部编码">
          <pb-input v-model.trim="skuForm.externalCode" placeholder="请输入外部编码"></pb-input>
        </el-form-item>
        <el-form-item label="保质期（天）" prop="qualityGuaranteePeriod">
          <pb-input v-model.trim="skuForm.qualityGuaranteePeriod" maxlength="5" placeholder="请输入保质期"></pb-input>
        </el-form-item>
        <el-form-item label="安全库存" prop="inventoryWarningQty">
          <pb-input v-model.trim="skuForm.inventoryWarningQty" maxlength="10" placeholder="请输入安全库存"></pb-input>
        </el-form-item>


      </el-form>
    </div>
  </pb-popup>
</template>

<script setup lang="ts">
import { upperLetter } from "@/utils/upperLetter";
import { getUnitsList } from '@/api/Units'
import { getSkuClassTreeApi } from "@/utils/globalFn";
import { getSkuCode, getCheckSkukName, addSkuInfo, setSkuInfo } from '@/api/Sku'
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
import { getSpuInfoList } from '@/api/Spu'

const emits = defineEmits(['refresh'])
const props = defineProps({
  purCycle: {
    type: Array
  }
})
const isShow = ref(false);
const innerVisible = ref(false);
const loading = ref(false)

const treeData = ref(null)

const formOrigin = () => ({
  skuCode: null,
  mnemonicCode: null,
  skuClassCode: null,
  skuName: null,
  accountingUnit: null,
  inventoryUnit: null,
  minimumUnit: null,
  isStocked: 1,
  specifications: null,
  unitWeight: null,
  lossRate: 0,
  recoveryRate: 100,
  purchasingCycle: 'week',
  placeOrigin: null,
  brand: null,
  barCode: null,
  externalCode: null,
  qualityGuaranteePeriod: null,
  inventoryWarningQty: null,
  inventoryScaleFactor: null,
  minimumScaleFactor: null,
  season: [],
  spuCode: "",
  spuCommonlyName: "",
  pic: null,
});

let skuForm = ref(formOrigin());

const rules = reactive({
  skuClassCode: [
    { required: true, message: "此项必填", trigger: ["blur", "change"] },
  ],
  accountingUnit: [
    { required: true, message: "此项必填", trigger: ["blur", "change"] },
  ],
  inventoryUnit: [
    { required: true, message: "此项必填", trigger: ["blur", "change"] },
  ],
  mnemonicCode: [
    { pattern: /^(?![0-9]+$)[A-Z0-9]{1,50}$/, message: "必须为大写字母或数字", trigger: ["blur", "change"] },
  ],
  skuName: [{ required: true, message: "此项必填", trigger: ["blur", "change"] },
  {
    validator(rule, value, callback) {
      checkName(value).then(res => {
        if (res) {
          return callback('SKU名称已存在')
        } else {
          callback()
        }
      })
    }
  }

  ],
  recoveryRate: [
    {
      required: true,
      pattern: /^(0|[1-9][0-9]*)+(.[0-9]{1,2})?$/,
      message: "最多包含1-10位数字且至多两位小数",
      trigger: ['blur', 'change'],
    },
  ],
  barCode: {
    required: false,
    pattern: /^[A-Za-z0-9]{4,10}$/,
    message: "必须为4-10位数字或字母",
    trigger: ["blur", "change"],
  },
  qualityGuaranteePeriod: {
    required: false,
    pattern: /^([1-9][0-9]*){1,5}$/,
    message: "最多包含1-5位数字且不能为0",
    trigger: ["blur", "change"],
  },
  lossRate: {
    required: false,
    pattern: /^(0|[1-9][0-9]*)+(.[0-9]{1,2})?$/,
    message: "最多包含1-10位数字且至多两位小数",
    trigger: ["blur", "change"],
  },
  inventoryWarningQty: {
    required: false,
    pattern: /^(0|[1-9][0-9]*){1,10}$/,
    message: "最多包含1-10位数字",
    trigger: ["blur", "change"],
  },
  unitWeight: {
    required: false,
    pattern: /^(0|[1-9][0-9]*)+(.[0-9]{1,2})?$/,
    message: "最多包含1-5位数字且至多两位小数",
    trigger: ["blur", "change"],
  },
  inventoryScaleFactor: {
    required: true,
    pattern: /^(0|[1-9][0-9]*)+(.[0-9]{1,2})?$/,
    message: "最多包含1-5位数字且至多两位小数",
    trigger: ["blur", "change"],
  },
  minimumScaleFactor: {
    required: true,
    pattern: /^(0|[1-9][0-9]*)+(.[0-9]{1,2})?$/,
    message: "最多包含1-5位数字且至多两位小数",
    trigger: ["blur", "change"],
  },
  specifications: {
    // required: false,
    // pattern: /^[\u4E00-\u9FA5A-Za-z0-9]{1,20}$/,
    // message: "最多包含1-20位数字、字母和中文",
    // trigger: ["blur", "change"],
  },
  brand: {
    required: false,
    pattern: /^[\u4E00-\u9FA5A-Za-z0-9]{1,10}$/,
    message: "最多包含1-10位数字、字母和中文",
    trigger: ["blur", "change"],
  },
  placeOrigin: {
    required: false,
    pattern: /^[\u4E00-\u9FA5A-Za-z]{1,10}$/,
    message: "最多包含1-10位字母和中文",
    trigger: ["blur", "change"],
  },
});

const seasonList = ref([
  { label: '春季' },
  { label: '夏季' },
  { label: '秋季' },
  { label: '冬季' },])

const showFn = (row) => {
  if (row) {
    skuForm.value = row
    skuForm.value.season = row.season ? row.season.split(',') : []
    conversionOne.value = skuForm.value.accountingUnitName
    conversionTwo.value = skuForm.value.inventoryUnitName
    conversionThree.value = skuForm.value.minimumUnitName
  }

  isShow.value = true;
};

// 获取计量单位
const unitsList = ref([])
const getUnitsListApi = () => {
  return new Promise<void>((resolve, reject) => {
    getUnitsList({ currentPage: 1, pageSize: -1, enableState: 1 }).then(res => {
      if (res.code == 2000) {
        unitsList.value = res.data.records
      }

    })
  })
}

// 生成sku编码
watch(
  () => skuForm.value.skuClassCode,
  (val) => {
    if (isShow.value && !skuForm.value.skuId) {
      getSkuCode({ skuClassCode: val }).then(res => {
        if (res.code == 2000) {
          skuForm.value.skuCode = res.data.skuCode
        }
      })

    }
  }
)

// sku名称、产地、品牌改变时生成助记码
watch(
  () => [skuForm.value.skuName, skuForm.value.placeOrigin, skuForm.value.brand],
  ([newName, newPlace, newBrand]) => {
    let name = newName ? upperLetter(newName) : ''
    let place = newPlace ? upperLetter(newPlace) : ''
    let brand = newBrand ? upperLetter(newBrand) : ''
    skuForm.value.mnemonicCode = `${brand}${place}${name}`
  }
)

const CheckMnemonic = (val) => {
  let reg = /^(?![0-9]+$)[A-Z0-9]{1,10}$/
  if (reg.test(val)) {
    innerVisible.value = false
  }
}


// 换算关系单位
const conversionOne = ref('')
const conversionTwo = ref('')
const conversionThree = ref('')

const changeOne = (item) => {
  conversionOne.value = item[0].packagingUnitName
  conversionTwo.value = item[0].packagingUnitName
  conversionThree.value = item[0].packagingUnitName
  skuForm.value.inventoryUnit = item[0].skuPackagingUnitId
  skuForm.value.minimumUnit = item[0].skuPackagingUnitId
}
const changeTwo = (item) => {
  conversionTwo.value = item[0].packagingUnitName
}
const changeThree = (item) => {
  conversionThree.value = item[0].packagingUnitName
}

//校验sku名称是否重复
const checkName = (val: string) => {
  return new Promise<void>((resolve, reject) => {
    let skuId = skuForm.value.skuId ? skuForm.value.skuId : null
    getCheckSkukName({ skuName: val, skuId }).then(res => {
      if (res.code == 2000) {
        if (res.data.skuNameExist) {
          resolve(true)
        } else {
          resolve(false)
        }
      }
    })
  })

}

// spu查询
const handleSearch = (queryString, callback) => {
  if (!queryString) {
    getSpuInfoList({
      spuName: null,
      currentPage: 1,
      pageSize: 15
    }).then(res => {
      for (let i of res.data.records) {
        i.value = i.spuName
      }
      callback(res.data.records)
    })
  } else {
    getSpuInfoList({
      spuName: queryString,
      currentPage: 1,
      pageSize: -1
    }).then(res => {
      for (let i of res.data.records) {
        i.value = i.spuName
      }
      callback(res.data.records)
    })
  }
}
// 选择
const handleSelect = (item) => {
  skuForm.value.spuCode = item.spuCode
}


const ruleFormRef = ref(null);
const ruleFormRef1 = ref(null);
const onSave = () => {
  Promise.all([
    ruleFormRef.value.validate(), ruleFormRef1.value.validate()
  ]).then(res => {
    if (skuForm.value.skuId) {
      setSkuInfoApi()
    } else {
      addSkuInfoApi()
    }
  })

};

// 添加
const addSkuInfoApi = () => {
  loading.value = true
  return new Promise<void>((resolve, reject) => {
    let { spuCommonlyName, ...args } = { ...skuForm.value }
    let str = ''
    args.season = args.season.join(',')
    addSkuInfo(args).then(res => {
      loading.value = false
      if (res.code == 2000) {
        createMessage({
          message: '添加成功'
        })
        isShow.value = false
        emits("refresh", skuForm.value.skuSupplyDetailsTempId ? skuForm.value.skuSupplyDetailsTempId : skuForm.value.orderPlanDetailsTempId ? skuForm.value.orderPlanDetailsTempId : '')
      }
    })
  })
}
// 修改
const setSkuInfoApi = () => {
  loading.value = true
  return new Promise<void>((resolve, reject) => {
    let {
      accountingUnit,
      inventoryUnit,
      minimumUnit,
      unitWeight,
      inventoryScaleFactor,
      minimumScaleFactor,
      specifications,
      purchasingCycle,
      placeOrigin,
      spuCode,
      barCode,
      externalCode,
      qualityGuaranteePeriod,
      inventoryWarningQty,
      lossRate,
      isStocked,
      brand,
      season,
      recoveryRate,
      pic,
      skuId,
      skuName,
    } = { ...skuForm.value }
    season = season.join(',')
    setSkuInfo({
      accountingUnit,
      inventoryUnit,
      minimumUnit,
      isStocked,
      specifications,
      unitWeight,
      lossRate,
      purchasingCycle,
      placeOrigin,
      brand,
      barCode,
      externalCode,
      qualityGuaranteePeriod,
      inventoryWarningQty,
      inventoryScaleFactor,
      minimumScaleFactor,
      season,
      spuCode,
      recoveryRate,
      pic,
      skuId,
      skuName,
    }).then(res => {
      loading.value = false
      if (res.code == 2000) {
        createMessage({
          message: '编辑成功'
        })
        isShow.value = false
        emits("refresh")
      }

    })
  })
}

// 关闭弹窗重置表单
const offPopup = () => {
  ruleFormRef.value.resetFields();
  ruleFormRef1.value.resetFields();
  skuForm.value = formOrigin();
  conversionTwo.value = ''
  conversionOne.value = ''
  conversionThree.value = ''
  innerVisible.value = false
};

onMounted(() => {
  getSkuClassTreeApi().then(res => {
    treeData.value = res
  })
  getUnitsListApi()
})

defineExpose({ showFn });
</script>

<style lang="scss" scoped>
::v-deep .el-input-group__append,
.el-input-group__prepend {
  background: rgba(0, 0, 0, 0.04);
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  padding: 0 12px;
}

.sub-label {
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
}
</style>